/*
package com.rykj.qxj.quartz;

import com.rykj.qxj.server.model.entity.TaskHistory;
import com.rykj.qxj.server.model.entity.TaskResult;
import com.rykj.qxj.server.services.TaskLogService;
import com.rykj.qxj.server.services.TaskService;
import com.rykj.qxj.server.util.SpringUtil;
import lombok.extern.log4j.Log4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


@Log4j
@Component
public class FieldTaskJob implements Job {

    @Autowired
    private  TaskService taskService;

    private final   String mysqlDriver = "com.mysql.jdbc.Driver";
    //1、更新任务执行时间
    //2、创建数据库连接
    //3、查询全量数据
    //4、校验数据插入详细日志记录
    @Override
    public void execute(JobExecutionContext context) throws RuntimeException {

        taskService = (TaskService) SpringUtil.getBean("taskService");
        JobKey key = context.getJobDetail().getKey();
        String taskName = key.getName();
        log.info("===="+taskName+"任务执行=====开始=====");
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        Integer taskId = dataMap.getIntValue("taskId");
        //更新执行时间
        taskService.updateTaskExecuteTime(taskId);
        TaskHistory taskHistory = new TaskHistory();
        taskHistory.setExecuteTime(new Date());
        taskHistory.setResultType("true");
        taskHistory.setTaskId(taskId);
        taskService.saveTaskHistory(taskHistory);
       // Integer taskHistoryId = taskHistory.getId();
        Map<String,Object> database = taskService.getDatabaseInfoByTaskId(taskId);
        //如果数据库或表被删除，就禁用、删除这个任务
        if(CollectionUtils.isEmpty(database)){
            log.info("====数据库或表已删除====所以任务队列删除任务==="+taskName+"==========");
            QuartzManager.removeJob(taskName);
            //修改任务状态为 禁用
            taskService.updateTaskStatus("disable",taskId);
        }

        List<Map<String, Object>> taskRules = taskService.getFieldRules(taskId);
        if (!CollectionUtils.isEmpty(taskRules)) {
            StringBuilder selectSql = new StringBuilder(" select ");
            List<String> fields =new ArrayList<>();
            for (Map<String,Object> tmap:taskRules ) {
                 String fieldName = (String) tmap.get("fieldName");
                 fields.add(fieldName);
                 selectSql.append(fieldName+",");
            }
            selectSql = selectSql.deleteCharAt(selectSql.lastIndexOf(","));
            selectSql.append( " from "+database.get("tableName"));
            //执行sql查询全量数据
            List<Map<String,Object>> checkDatas  =   executeSQLStatements(database,selectSql.toString(),fields);

            if(!CollectionUtils.isEmpty(checkDatas)){
                //规则检验日志数据
                List<TaskResult> taskLogs = new ArrayList<>();
                for (Map<String,Object> tmap:taskRules ) {
                    String fieldName = (String) tmap.get("fieldName");
                    String regulars = (String) tmap.get("regulars");
                    Integer fieldId = (Integer) tmap.get("fieldId");
                    for (Map<String,Object> dMap:checkDatas ) {
                       String fieldValue = (String)dMap.get(fieldName);
                      if(!Pattern.matches(regulars,fieldValue )){
                          //新增一条数据不匹配的校验日志
                          TaskResult taskResult = new TaskResult();
                          taskResult.setTaskHistoryId(taskHistory.getId());
                          taskResult.setFieldId(fieldId);
                          taskResult.setFieldValue(fieldValue);
                          taskResult.setCheckResult("error");
                          taskLogs.add(taskResult);
                      }
                    }
                }
                //插入日志记录
                if(!CollectionUtils.isEmpty(taskLogs)){
                    TaskLogService taskLogService = (TaskLogService) SpringUtil.getBean("taskLogService");
                    taskLogService.saveTaskLog(taskLogs);
                    taskHistory.setResultType("error");
                    taskService.updateTaskHistoryType(taskHistory);
                }
            }
        }
        log.info("===="+taskName+"任务执行=====结束=====");
    }

    */
/**
     * 执行数据库ddl语句
     * @param database
     * @param excutSql
     * @return
     *//*

    private   List<Map<String,Object>>  executeSQLStatements(Map<String,Object> database, String excutSql,List<String> fields) throws RuntimeException{
        List<Map<String,Object>> restMaps= new ArrayList<>();
        Connection conn = null;
        try {
            conn = createDatabaseConn(database);
            if (conn==null){
                log.error("创建数据库连接失败");
                throw  new RuntimeException("创建数据库连接失败");
            }
            PreparedStatement smt = conn.prepareStatement(excutSql);
            ResultSet resultSet = smt.executeQuery();

            while(resultSet.next()) {
                Map<String,Object> c = new HashMap<>();
                for (String field:fields ) {
                    c.put(field,resultSet.getString(field));
                }
                restMaps.add(c);
            }
           log.info("JDBC获取的数据为========"+restMaps);
        }catch (Exception e){
            log.error("创建连接超时或执行sql语句异常",e);
            throw  new RuntimeException("创建连接超时或执行sql语句异常");
        }finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("关闭数据库连接失败",e);
                    throw  new RuntimeException("关闭数据库连接失败");
                }
            }
        }
        return restMaps;
    }

    */
/**
     * 创建数据库连接
     *//*

    public Connection createDatabaseConn(Map<String,Object> database) throws  Exception{
        String databaseIP = (String) database.get("databaseIP");
        String port = (String) database.get("port");
        String databaseName = (String) database.get("databaseName");
        String userName = (String) database.get("userName");
        String password = (String) database.get("password");
        //连接数据库名，新建表及字段信息
        String databaseUrl = "jdbc:mysql://"+databaseIP+":"+port+"/"+databaseName+ "?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        try {
            Class.forName(mysqlDriver);
        } catch (ClassNotFoundException e) {
            throw  new Exception("未安装mysql驱动连接程序");
        }
        try {
            DriverManager.setLoginTimeout(3);
            conn = DriverManager.getConnection(databaseUrl ,userName, password);
            if(conn== null){
                log.error("创建连接失败");
                return  null;
            }
            log.info(databaseIP+":创建连接数据库成功！");
        } catch (SQLException e) {
            log.error("创建连接超时",e);
            throw  new Exception("创建连接超时");
        }
        return conn;
    }
}
*/
